package com.shuhua.taskServer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuhua.common.result.Result;
import com.shuhua.pojo.dto.TeamApplyAuditDTO;
import com.shuhua.pojo.dto.TeamApplyDTO;
import com.shuhua.pojo.entity.Craftsman;
import com.shuhua.pojo.entity.Team;
import com.shuhua.pojo.entity.TeamApply;
import com.shuhua.pojo.entity.TeamMember;
import com.shuhua.pojo.vo.CraftsmanSimpleVO;
import com.shuhua.pojo.vo.TeamApplyVO;
import com.shuhua.pojo.vo.TeamMemberVO;
import com.shuhua.taskServer.mapper.CraftsmanMapper;
import com.shuhua.taskServer.mapper.TeamApplyMapper;
import com.shuhua.taskServer.mapper.TeamMapper;
import com.shuhua.taskServer.mapper.TeamMemberMapper;
import com.shuhua.taskServer.service.TeamApplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 班组申请服务实现类
 */
@Service
@RequiredArgsConstructor
public class TeamApplyServiceImpl extends ServiceImpl<TeamApplyMapper, TeamApply> implements TeamApplyService {

    private final TeamMapper teamMapper;
    private final CraftsmanMapper craftsmanMapper;
    private final TeamMemberMapper teamMemberMapper;
    private final TeamApplyMapper teamApplyMapper;

    @Override
    public Result<TeamApply> applyJoinTeam(TeamApplyDTO teamApplyDTO) {
        // 验证班组是否存在
        Team team = teamMapper.selectById(teamApplyDTO.getTeamId());
        if (team == null) {
            return Result.error("班组不存在");
        }

        // 验证班组状态
        if (team.getState() != 1) {
            return Result.error("班组未通过审核或已被禁用");
        }

        // 验证工匠是否存在
        Craftsman craftsman = craftsmanMapper.selectById(teamApplyDTO.getCraftsmanId());
        if (craftsman == null) {
            return Result.error("工匠不存在");
        }

        // 检查是否已经是班组成员
        LambdaQueryWrapper<TeamMember> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.eq(TeamMember::getTeamId, teamApplyDTO.getTeamId())
                .eq(TeamMember::getCraftsmanId, teamApplyDTO.getCraftsmanId());
        long memberCount = teamMemberMapper.selectCount(memberQueryWrapper);
        if (memberCount > 0) {
            return Result.error("已经是该班组成员");
        }

        // 检查是否已经申请过
        LambdaQueryWrapper<TeamApply> applyQueryWrapper = new LambdaQueryWrapper<>();
        applyQueryWrapper.eq(TeamApply::getTeamId, teamApplyDTO.getTeamId())
                .eq(TeamApply::getCraftsmanId, teamApplyDTO.getCraftsmanId())
                .eq(TeamApply::getStatus, 0); // 状态为待审核
        long applyCount = count(applyQueryWrapper);
        if (applyCount > 0) {
            return Result.error("已经申请过该班组，请等待审核");
        }

        // 创建申请记录
        TeamApply apply = new TeamApply();
        apply.setTeamId(teamApplyDTO.getTeamId());
        apply.setCraftsmanId(teamApplyDTO.getCraftsmanId());
        apply.setApplyTime(new Date());
        apply.setStatus(0); // 待审核状态
        save(apply);

        return Result.success("申请提交成功，请等待审核", apply);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<TeamApply> auditTeamApply(TeamApplyAuditDTO teamApplyAuditDTO) {
        // 检查申请是否存在
        TeamApply apply = getById(teamApplyAuditDTO.getApplyId());
        if (apply == null) {
            return Result.error("申请不存在");
        }

        // 检查申请状态
        if (apply.getStatus() != 0) {
            return Result.error("申请已处理，无法重复审核");
        }

        // 获取班组和工匠信息
        Team team = teamMapper.selectById(apply.getTeamId());
        Craftsman craftsman = craftsmanMapper.selectById(apply.getCraftsmanId());

        if (team == null || craftsman == null) {
            return Result.error("班组或工匠不存在");
        }

        // 更新申请状态
        apply.setStatus(teamApplyAuditDTO.getStatus());
        apply.setAuditTime(new Date());
        apply.setAuditRemark(teamApplyAuditDTO.getAuditRemark());
        updateById(apply);

        // 如果审核通过，添加为班组成员
        if (teamApplyAuditDTO.getStatus() == 1) {
            // 创建班组成员记录
            TeamMember teamMember = new TeamMember();
            teamMember.setTeamId(apply.getTeamId());
            teamMember.setCraftsmanId(apply.getCraftsmanId());
            teamMember.setJoinTime(new Date());
            teamMemberMapper.insert(teamMember);

            // 更新班组成员数量
            team.setMemberNum(team.getMemberNum() + 1);
            teamMapper.updateById(team);

            return Result.success("已通过申请，工匠已成为班组成员", apply);
        } else {
            return Result.success("已拒绝申请", apply);
        }
    }

    @Override
    public Result<List<TeamApplyVO>> getTeamApplies(Long teamId) {
        // 验证班组是否存在
        Team team = teamMapper.selectById(teamId);
        if (team == null) {
            return Result.error("班组不存在");
        }

        // 查询班组申请（包含申请人详细信息）
        List<TeamApplyVO> applies = new ArrayList<>();
        
        // 查询申请列表
        LambdaQueryWrapper<TeamApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamApply::getTeamId, teamId);
        List<TeamApply> applyList = list(queryWrapper);
        
        // 组装申请详情
        for (TeamApply apply : applyList) {
            TeamApplyVO vo = new TeamApplyVO();
            // 查询班组信息
            Team applyTeam = teamMapper.selectById(apply.getTeamId());
            vo.setTeam(applyTeam);
            
            // 查询申请人详细信息，并转换为CraftsmanSimpleVO
            Craftsman craftsman = craftsmanMapper.selectById(apply.getCraftsmanId());
            if (craftsman != null) {
                CraftsmanSimpleVO craftsmanSimpleVO = new CraftsmanSimpleVO();
                BeanUtils.copyProperties(craftsman, craftsmanSimpleVO);
                vo.setTeamLeader(craftsmanSimpleVO);
            }
            
            applies.add(vo);
        }

        return Result.success(applies);
    }

    @Override
    public Result<List<TeamApplyVO>> getCraftsmanApplies(Long craftsmanId) {
        // 验证工匠是否存在
        Craftsman craftsman = craftsmanMapper.selectById(craftsmanId);
        if (craftsman == null) {
            return Result.error("工匠不存在");
        }

        // 查询工匠申请（包含申请人详细信息）
        List<TeamApplyVO> applies = new ArrayList<>();
        
        // 查询申请列表
        LambdaQueryWrapper<TeamApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamApply::getCraftsmanId, craftsmanId);
        List<TeamApply> applyList = list(queryWrapper);
        
        // 组装申请详情
        for (TeamApply apply : applyList) {
            TeamApplyVO vo = new TeamApplyVO();
            // 查询班组信息
            Team applyTeam = teamMapper.selectById(apply.getTeamId());
            vo.setTeam(applyTeam);
            
            // 转换工匠信息为CraftsmanSimpleVO
            CraftsmanSimpleVO craftsmanSimpleVO = new CraftsmanSimpleVO();
            BeanUtils.copyProperties(craftsman, craftsmanSimpleVO);
            vo.setTeamLeader(craftsmanSimpleVO);
            
            applies.add(vo);
        }

        return Result.success(applies);
    }
} 